import { getProtocolWsUrl } from "@/utils/ws";

class VoiceSocket {
  socket: WebSocket | null = null;
  text: string = "";

  constructor() {
    this.socket = null;
  }

  public randnum() {
    return window.crypto.getRandomValues(new Uint8Array(1)) * 0.001;
  }

  public _getRandomString(len: number) {
    len = len || 32;
    var $chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678"; // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
    var maxPos = $chars.length;
    var uid = "";
    for (let i = 0; i < len; i++) {
      uid += $chars.charAt(Math.floor(this.randnum() * maxPos));
    }
    return uid;
  }

  public __show2(e) {
    this.text = "";
    if (e.ws != null) {
      for (let i = 0; i < e.ws.length; i++) {
        var cw = e.ws[i].cw;
        if (cw != null) {
          if (cw[0].rl !== 0) {
            this.text =
              this.text + "<br/>" + "[" + cw[0].rl + "]" + cw[0].w + " ";
          } else {
            this.text = this.text + cw[0].w + " ";
          }
        }
      }
    }
  }

  public start({
    onMessage,
    onClose,
  }: {
    onMessage?: (text: string) => void;
    onClose?: () => void;
  }) {
    return new Promise((reslove, reject) => {
      const sessionId = "ASTDEMO_" + this._getRandomString(8);
      // const wsuri = "wss://" + document.location.host + "/tuling/ast/v2/" + sessionId + "?appId=10101&bizId=123&bizName=AST_DEMO";
      // ws://10.18.1.78:32601/tuling/ast/v2/

      const wsuri = getProtocolWsUrl(
        `${window.location.host}/cnpc-web/voice/websocket/` +
        sessionId +
        "?appId=10101&bizId=123&bizName=WebSocket&lan=chin&sr=16000&bps=16&fs=4096"
      );
      console.log("语音识别访问服务地址：" + wsuri);
      this.socket = new WebSocket(wsuri);
      this.socket.onopen = () => {
        reslove(this.socket);
      };
      this.socket.onmessage = (e) => {
        var jsonResponse = JSON.parse(e.data);
        this.__show2(jsonResponse);
        onMessage && onMessage(this.text);
      };
      this.socket.onclose = (e) => {
        if (e.code === 1001) {
          onClose && onClose();
        }
      };
      this.socket.onerror = (err) => {
        reject(err);
      };
    });
  }
  public send(data: any) {
    if (!this.socket) return;
    if (this.socket.readyState === 1) {
      this.socket.send(data);
    }
  }
  public close() {
    if (!this.socket) return;
    this.socket.close();
    this.socket = null;
  }
}

export default VoiceSocket;
